#!/usr/bin/env python3
"""
测试运行器脚本

这个脚本用于运行项目测试，通过环境变量和配置隔离来避免系统级插件冲突。
"""

import os
import sys
import subprocess
import tempfile
from pathlib import Path


def create_isolated_pytest_config():
    """创建隔离的 pytest 配置文件"""
    config_content = """[tool:pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = 
    --strict-markers
    --strict-config
    --verbose
    --tb=short
    --cov=minicoder
    --cov-report=term-missing
    --cov-report=html:htmlcov
    --cov-report=xml
    --color=yes
markers =
    unit: 单元测试
    integration: 集成测试
    slow: 运行较慢的测试
    network: 需要网络连接的测试
filterwarnings =
    ignore::DeprecationWarning
    ignore::PendingDeprecationWarning
    ignore::UserWarning
"""
    
    # 创建临时配置文件
    temp_dir = Path(tempfile.mkdtemp())
    config_file = temp_dir / "pytest.ini"
    config_file.write_text(config_content)
    
    return temp_dir, config_file


def run_tests():
    """运行测试"""
    project_root = Path(__file__).parent.absolute()
    src_path = project_root / 'src'
    
    # 设置环境变量
    env = os.environ.copy()
    
    # 设置 PYTHONPATH
    if 'PYTHONPATH' in env:
        env['PYTHONPATH'] = f"{src_path}:{env['PYTHONPATH']}"
    else:
        env['PYTHONPATH'] = str(src_path)
    
    # 创建隔离的 pytest 配置
    temp_dir, config_file = create_isolated_pytest_config()
    
    try:
        # 使用临时配置文件运行测试
        cmd = [
            sys.executable, '-m', 'pytest',
            'tests/',
            '-v',
            '--tb=short',
            '--color=yes',
            f'--config-file={config_file}'
        ]
        
        print("运行测试命令：", ' '.join(cmd))
        print("PYTHONPATH:", env.get('PYTHONPATH', ''))
        print("配置文件:", config_file)
        print("-" * 50)
        
        result = subprocess.run(cmd, cwd=project_root, env=env)
        return result.returncode
        
    finally:
        # 清理临时文件
        import shutil
        shutil.rmtree(temp_dir)


if __name__ == '__main__':
    sys.exit(run_tests())
